package de.wesemann.mediahandbook.le.activity;

import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import de.wesemann.jdedun.entities.mediahandbook.branches.MediahandbookBranche;
import de.wesemann.mediahandbook.le.R;
import de.wesemann.mediahandbook.le.activity.helper.AbstractAsyncTask;
import de.wesemann.mediahandbook.le.activity.helper.AbstractListActivity;
import de.wesemann.mediahandbook.le.adapter.BranchAdapter;
import de.wesemann.mediahandbook.le.util.BranchUtil;
import de.wesemann.mediahandbook.le.util.LoadStyle;
import de.wesemann.mediahandbook.le.widget.TitleWidget;

public class BranchOverview extends AbstractListActivity {
	private static final String LOG_TAG = BranchOverview.class.getSimpleName();
	public static final String BRANCH_TAG = "MediahandbookBranch";
	private TitleWidget titleWidget;
	// private MediahandbookBranchesContainer mBranchContainer;
	private BranchAdapter mBranchAdapt;
	private List<MediahandbookBranche> mBranches;
	private LoadStyle loadStyle;
	private LoadItemsTask mLoadItemsTask;
	private String mSearchValue;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.d(LOG_TAG, "onCreate()");
		setContentView(R.layout.branchs_overview);
		setUpTitleWidget();
		loadStyle = LoadStyle.All;
		Object retained = getLastNonConfigurationInstance();
		if (retained instanceof LoadItemsTask) {
			Log.d(LOG_TAG, "Reclaiming previous background task LoadItems.");
			mLoadItemsTask = (LoadItemsTask) retained;
			mLoadItemsTask.setActivity(this);
		} else {
			mLoadItemsTask = new LoadItemsTask(this);
			mLoadItemsTask.execute();
		}
	}

	private void setUpTitleWidget() {
		titleWidget = (TitleWidget) findViewById(R.id.co_titleWidget);
		titleWidget.setTitle(getString(R.string.branches));
		titleWidget.setLeftIcon(R.drawable.bu_house_conf);

		titleWidget.hideProgressBar();
	}

	private void createList() {
		mBranchAdapt = new BranchAdapter(this, mBranches);

		setListAdapter(mBranchAdapt);
	}

	public void onSearchClick(View view) {
		if (view.getId() == R.id.title_search) {
			// Toast.makeText(this, "search clicked",
			// Toast.LENGTH_SHORT).show();
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle(getString(R.string.search_title));
			final EditText edit = new EditText(this);
			builder.setView(edit);

			builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {
					Editable value = edit.getText();
					if (value.toString().length() != 0) {
						mSearchValue = value.toString().trim();
						mSearchValue = mSearchValue.replace(" ", "%20");
						loadStyle = LoadStyle.Search;
						Log.d(LOG_TAG, "I'm looking for " + mSearchValue);
						mLoadItemsTask = new LoadItemsTask(BranchOverview.this);
						mLoadItemsTask.execute(mSearchValue);
					}
				}
			});

			builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {
					// Canceled.
				}
			});

			builder.show();

		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.ListActivity#onListItemClick(android.widget.ListView,
	 * android.view.View, int, long)
	 */
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		MediahandbookBranche branch = (MediahandbookBranche) getListView().getItemAtPosition(position);
		Intent intent = new Intent(this, CompaniesOverview.class);
		intent.putExtra(BRANCH_TAG, branch);
		startActivity(intent);
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
	}

	private class LoadItemsTask extends AbstractAsyncTask<String, Void, List<MediahandbookBranche>> {

		private List<MediahandbookBranche> branches;

		private LoadItemsTask(BranchOverview activity) {
			super(activity);
		}

		@Override
		protected List<MediahandbookBranche> doInBackground(String... params) {
			try {
				if (loadStyle.equals(LoadStyle.Search)) {
					Log.d(LOG_TAG, "Search");
					branches = BranchUtil.searchBrnachesByName(params[0]);
				} else if (loadStyle.equals(LoadStyle.All)) {
					Log.d(LOG_TAG, "All");
					branches = BranchUtil.getAllBranches();
				}
			} catch (FileNotFoundException e) {
				Log.e(LOG_TAG, e.getMessage());
				cancel(true);
			}
			// delete all branches without companies
			Log.d(LOG_TAG, "found " + branches.size() + " branches");
			List<MediahandbookBranche> branchesWithCompanies = new ArrayList<MediahandbookBranche>();
			for (MediahandbookBranche branch : branches) {
				if (branch.getCompanies() != null && !branch.getCompanies().isEmpty()) {
					Log.d(LOG_TAG, branch.getName() + " has companies => add");
					branchesWithCompanies.add(branch);
				}
			}
			branches.clear();
			branches.addAll(branchesWithCompanies);
			branchesWithCompanies = null;
			Log.d(LOG_TAG, branches.size() + " branches left");
			return branches;
		}

		@Override
		protected void onPreExecute() {
			Log.d(LOG_TAG, "PRE Executing");
			activity.showDialog(LOADING_DIALOG);

		}

	}

	@Override
	public void reload(AbstractAsyncTask<?, ?, ?> task) {

		dismissDialog(LOADING_DIALOG);
		Toast.makeText(this, getString(R.string.error_while_loading), Toast.LENGTH_LONG).show();
		if (task.getreLoadTries() < 3) {
			if (task instanceof LoadItemsTask) {
				mLoadItemsTask.execute(mSearchValue);
			}
		}
	}

	@Override
	public void onTaskCompleted(AbstractAsyncTask<?, ?, ?> task) {
		try {
			mBranches = mLoadItemsTask.get();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}

		createList();
		if (mShownDialog) {
			dismissDialog(LOADING_DIALOG);
			Toast.makeText(this, R.string.finished, Toast.LENGTH_LONG).show();
		}
	}

	/**
	 * After a screen orientation change, this method is invoked. As we're going
	 * to state save the task, we can no longer associate it with the Activity
	 * that is going to be destroyed here.
	 */
	@Override
	public Object onRetainNonConfigurationInstance() {
		if (mLoadItemsTask != null) {
			Log.d(LOG_TAG, "Save the LoadItemsTask");
			mLoadItemsTask.setActivity(null);
			return mLoadItemsTask;
		}
		return null;

	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}

	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		super.onRestart();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}

	@Override
	protected void onRestoreInstanceState(Bundle state) {
		// TODO Auto-generated method stub
		super.onRestoreInstanceState(state);
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		// TODO Auto-generated method stub
		super.onSaveInstanceState(outState);
	}

}
